package com.wd.base.ui;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.wd.base.util.TUtil;

/**
 * @author W4255
 * @data [ 2021/2/4 20:13]
 * @Description NA
 */
public abstract class BaseFragment<T extends ViewModel> extends Fragment {
    private View rootView;
    protected T mViewModel;

    /**
     * 获取TAG
     *
     * @return 返回TAG
     */
    protected abstract String getLogTag();

    /**
     * 设置布局layout
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 初始化views
     *
     * @param view
     */
    protected abstract void initView(View view);

    /**
     * 加载数据
     */
    protected void loadData() {

    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(getLayoutId(), null, false);
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initViewModel();
        loadData();
    }

    /**
     * 初始化vm
     */
    protected void initViewModel() {
        mViewModel = getViewModel((Class<T>) TUtil.getInstance(this, 0));
    }

    /**
     * 获取指定类型的VM实例
     *
     * @param viewModelClazz VM的类实例
     * @param <T>            VM类型
     * @return VM对象
     */
    protected <T extends ViewModel> T getViewModel(Class<T> viewModelClazz) {
        if (viewModelClazz == null) {
            return null;
        }
        if (null != getActivity()) {
            return new ViewModelProvider(getActivity()).get(viewModelClazz);
        } else {
            return new ViewModelProvider(this).get(viewModelClazz);
        }

    }
}
